import java.util.Random;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-09-08
 * Time:23:41
 */
public class BlockingQueue {
    private int[] items = new int[1000];
    private volatile int size = 0;
    private int head = 0;
    private int end = 0;

    public void put(int value) throws InterruptedException {
        synchronized (this) {
            // 使用while防止notifyAll()时该线程被唤醒，但是当轮到该线程时，队列又满了的情况
            while (size == items.length) {
                wait();
            }
            items[end] = value;
            end = end + 1;
            if (end >= items.length) {
                end = 0;
            }
            size++;
            notifyAll();
        }
    }

    public int take() throws InterruptedException {
        int ret = 0;
        synchronized (this) {
            while (size == 0) {
                wait();
            }
            ret = items[head];
            head = head + 1;
            if (head >= items.length) {
                head = 0;
            }
            size--;
            notifyAll();
        }
        return ret;
    }

    //测试
    public static void main(String[] args) {
        BlockingQueue blockingQueue = new BlockingQueue();

        Thread customer = new Thread(()-> {
            while (true) {
                try {
                    int value = blockingQueue.take();
                    System.out.println("消费元素：" + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者");
        customer.start();

        Thread producer = new Thread(()->{
            Random random = new Random();
            while (true) {
                try {
                    int num = random.nextInt(1000);
                    System.out.println("生产元素：" + num);
                    blockingQueue.put(num);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者");
        producer.start();

        try {
            customer.join();
            producer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
